package com.test.springboot.alicloudsms.controller;

import com.aliyuncs.utils.StringUtils;
import com.test.springboot.alicloudsms.service.AlicloudSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/8/11 2:20
 * @package com.test.springboot.alicloudsms.controller
 * @description 文件说明
 */
@RestController
@CrossOrigin // 跨域支持
public class AlicloudSmsController {
    @Autowired
    private AlicloudSmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send/{phone}")
    public String code(@PathVariable("phone") String phone) {
        // 调用方法（模拟真实业务 redis）

        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return phone + ":" + code + "尚未过期";
        }

        // 生成 验证码并存储到redis 中
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, Object> hashMap = new HashMap<>();

        hashMap.put("code", code);

        boolean isSendSuccess = smsService.sendSms(phone, "SMS_232075122", hashMap);

        if (isSendSuccess) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return phone + ":" + code + "发送成功";
        } else {
            return "发送失败";
        }
    }
}
